/*
 Copyright 2007 Ole Rogeberg

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
package org.lifeyears.web.action;

import java.util.List;

import org.lifeyears.model.Donation;
import org.lifeyears.model.User;
import org.lifeyears.services.DonationService;
import org.lifeyears.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * Action for displaying a user profile
 * 
 * @author Eivind Berg Johannessen
 */
@Scope( "prototype" )
@Component
public class UserAction
    extends AbstractLifeyearsAction
{
    @Autowired
    protected DonationService donationService;

    @Autowired
    protected UserService userService;

    protected Long userid;

    public void setDonationService( DonationService donationService )
    {
        this.donationService = donationService;
    }

    public void setUserService( UserService userService )
    {
        this.userService = userService;
    }

    public void setUserId( int userid )
    {
        this.userid = new Long( userid );
    }

    @Override
    public String execute()
        throws Exception
    {
        if ( getUser() == null )
        {
            addActionError( getText( "user.doesnotexist" ) );
            return ERROR;
        }

        return SUCCESS;
    }

    public User getUser()
    {
        return (userid == null) ? getLoggedInUser() : userService.get( userid );
    }

    public int getLifeyearsSaved()
    {
        int i = 0;
        for ( Donation d : getDonations() )
        {
            i += d.getLifeyears();
        }
        return i;
    }

    public List<Donation> getDonations()
    {
        // TODO: Make use of User.getDonations().
        // NOTE: At the moment there is a problem with lazy-loading
        // return getUser().getDonations();
        return donationService.getDonations( getUser() );
    }

}
